package com.huiyujinrong.qiangdanbao.permission;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * 权限 基类 Fragment
 * Created by April丶 on 2017/1/13.
 */

public class PerMissionsFragment extends Fragment {

    private int REQUEST_CODE_PERMISSION = 0x00002;

    /**
     * 请求权限
     *
     * @param permissions
     * @param requestCode
     */
    protected void requestPermission(String[] permissions, int requestCode) {
        this.REQUEST_CODE_PERMISSION = requestCode;
        if (myCheckPermissions(permissions)) {
            permissionSuccess(requestCode);
        } else {
            List<String> needPermis = getDeniedPermissions(permissions);
            ActivityCompat.requestPermissions(getActivity(), needPermis.toArray(new String[needPermis.size()]), REQUEST_CODE_PERMISSION);
        }
    }

    //检测该权限列表所有的权限是否已被授权
    private boolean myCheckPermissions(String[] permissions) {
        if (Build.VERSION.SDK_INT < 23) {
            //android版本小于6.0
            return true;
        }
        //android版本大于6.0
        for (String permi : permissions) {
            if (PackageManager.PERMISSION_GRANTED !=
                    ContextCompat.checkSelfPermission(getActivity(), permi)) {
                return false;
            }
        }
        return true;
    }

    //获取权限集中需要申请的权限列表
    private List<String> getDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissionList = new ArrayList<>();
        for (String permi : permissions) {
            if (PackageManager.PERMISSION_DENIED == ContextCompat.checkSelfPermission(getActivity(), permi)
                    || ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), permi)) {
                needRequestPermissionList.add(permi);
            }
        }
        return needRequestPermissionList;
    }

    /**
     * 系统请求权限回调
     *
     * @param requestCode  请求码
     * @param permissions  权限列表
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (REQUEST_CODE_PERMISSION == requestCode) {
            if (isVerifyPermissions(grantResults)) {
                permissionSuccess(requestCode);
            } else {
                permissionFail(requestCode);
            }
        }
    }

    //确认所有权限已被授权
    private boolean isVerifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (PackageManager.PERMISSION_GRANTED != result) {
                return false;
            }
        }
        return true;
    }

    //显示所有提示对话框
    private void showTipsDialog() {
        new AlertDialog.Builder(getActivity())
                .setTitle("授权失败提示信息")
                .setMessage("因缺少必要权限，该功能暂时无法使用。\n" +
                        "如果需要，请前往设置中心确认授权。")
                .setNegativeButton("知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                })
                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        toSettings();
                    }
                }).show();
    }

    //启动系统设置
    private void toSettings() {
        Intent intent = new Intent(Settings.ACTION_SETTINGS);//系统设置界面
        startActivity(intent);
    }

    /**
     * 权限申请成功回调
     *
     * @param requestCode 请求码
     */
    protected void permissionSuccess(int requestCode) {

    }

    /**
     * 权限申请失败回调
     *
     * @param requestCode 请求码
     */
    protected void permissionFail(int requestCode) {
        showTipsDialog();
    }

}
